@file:Suppress("UNCHECKED_CAST")

package com.cqhz.quwan.util

import android.support.annotation.LayoutRes
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.Transformation

/**
 * Created by WYZ on 2018/3/16.
 */
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
    return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}
fun <T> View.attr(
        attrIndex:Int,
        default:T,
        resourceId:Boolean = false,
        color:Boolean = false):Lazy<T?>{
    val c = this::class.java.getDeclaredField("attrs")
    c.isAccessible = true
    val attrs:AttributeSet = c.get(this) as AttributeSet
    val styleableClassName = "${this.context.packageName}.R\$styleable"
    val styleableClass = this::class.java.classLoader.loadClass(styleableClassName)
    val styleableClassField = styleableClass.getField(this::class.java.simpleName)
    val styleableAttrSet:IntArray? = styleableClassField.get(styleableClass) as IntArray
    val typedArray = context.obtainStyledAttributes(attrs,styleableAttrSet)
    val out:T? = when(default){
        is String -> typedArray.getString(attrIndex) as? T
        is Int -> when{
            resourceId -> typedArray.getResourceId(attrIndex,default) as? T
            color -> typedArray.getColor(attrIndex,default) as? T
            else -> typedArray.getInt(attrIndex,default) as? T
        }
        is Float -> typedArray.getFloat(attrIndex,default) as? T
        else -> null
    }
    typedArray.recycle()
    return lazy {out}
}
fun <T:View> ViewGroup.loadLayout(layoutId:Int):Lazy<T>{
    return lazy { inflate(layoutId,false) as T }
}


fun View.startRotateAnimation(start:Int,angle:Int,time:Long):Animation{
    val v = this
    val animation = object:Animation(){
        override fun applyTransformation(interpolatedTime: Float, t: Transformation?) {
            v.rotation = interpolatedTime*angle+start
        }
    }
    animation.duration = time
    animation.setAnimationListener(null)
    this.startAnimation(animation)
    return animation
}